#include "unixhead.h"

#include <string>
#include <iostream>
using std::cout;
using std::endl;
using std::string;

class HttpServer
{
public:
    HttpServer(const string & ip, unsigned short port)
    : _listenfd(-1)
    , _ip(ip)
    , _port(port)
    {}

    ~HttpServer()
    {
        close(_listenfd);
    }

    void start()
    {
        _listenfd = socket(AF_INET, SOCK_STREAM, 0);
        if(_listenfd < 0) {
            perror("socket");
            return;
        }

        struct sockaddr_in serveraddr;
        memset(&serveraddr, 0, sizeof(serveraddr));
        serveraddr.sin_family = AF_INET;
        serveraddr.sin_port = htons(_port);
        serveraddr.sin_addr.s_addr = inet_addr(_ip.c_str());

        int on = 1;
        setsockopt(_listenfd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));

        int ret = ::bind(_listenfd, (struct sockaddr*)&serveraddr, sizeof(serveraddr));
        if(ret < 0) {
            perror("bind");
            return;
        }

        ret = ::listen(_listenfd, 128);
        if(ret < 0) {
            perror("listen");
            return;
        }
    }

    void recvAndShow()
    {
        while(1) {
            int peerfd = ::accept(_listenfd, nullptr, nullptr);

            if(peerfd > 0) {
                char buff[1024] = {0};
                recv(peerfd, buff, 1024, 0);
                printf(">>buff:\n%s\n", buff);
            }
            close(peerfd);
        }
    }

private:
    int _listenfd;
    string _ip;
    unsigned short _port;
};

void test0()
{
    HttpServer server("0.0.0.0", 1280);
    server.start();
    server.recvAndShow();
}


int main()
{
    test0();
    return 0;
}

